package com.wuhunyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wuhunyu.commonutils.check.Check;
import com.wuhunyu.commonutils.jwt.JwtUtils;
import com.wuhunyu.commonutils.jwt.MD5;
import com.wuhunyu.commonutils.result.CommonResult;
import com.wuhunyu.entity.User;
import com.wuhunyu.mapper.UserMapper;
import com.wuhunyu.service.LoginService;
import com.wuhunyu.servicebase.exception.Assert;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录业务层实现类
 *
 * @author wuhunyu
 * @version 1.0
 * @date 2021-02-02 11:30
 */
@Service("loginService")
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserMapper userMapper;

    @Override
    public CommonResult login(String username, String password) {
        // 校验参数
        Assert.isRight(Check.isBlank(username), "用户名不能为空");
        Assert.isRight(Check.isBlank(password), "密码不能为空");
        // 根据用户名查询用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "password");
        queryWrapper.eq("username", username);
        List<User> users = userMapper.selectList(queryWrapper);
        // 校验结果集
        Assert.isRight(users == null || users.size() != 1, "用户名不存在或用户名错误");
        String p = users.get(0).getPassword();
        // 校验密码
        Assert.isRight(!p.equals(MD5.encrypt(username + password)), "密码错误");
        // 封装结果集
        Map<String, Object> map = new HashMap<>(16);
        // token
        map.put("token", JwtUtils.getJwtToken(users.get(0).getId(), username));
        return CommonResult.success("登录成功", map);
    }

    @Override
    public CommonResult userInfo(String token) {
        String userId = JwtUtils.getMemberIdByJwtTokenString(token);
        Assert.isRight(Check.isBlank(userId), "解析token失败");
        // 查询用户信息
        User user = userMapper.selectById(userId);
        // 查询用户所拥有的所有角色
        List<String> roles = userMapper.selectUserInfo(userId);
        // 校验结果集
        Assert.isRight(Check.isBlank(user), "查询用户信息失败");
        // 封装用户数据
        Map<String, Object> map = new HashMap<>(16);
        map.put("roles", roles.toString());
        map.put("name", user.getNickName());
        map.put("avatar", user.getSalt());
        return CommonResult.success("获取用户信息成功", map);
    }

    @Override
    public CommonResult logout() {
        return null;
    }
}
